import React, { useState, useCallback, useEffect, useContext } from 'react';
import styles from './index.module.less';
import Header from '../../components/Header';
import { getMiningList, withdraw, getPledgeLog, convert, getPrice } from '@app/common/api';
import { Toast } from 'antd-mobile';
import { AllContext } from '../../AllContext';

const tabs = ['交换', '提取', '記錄'];
const kyHeader = ['時間', '礦工', '申請'];
let time = null;
let falg = false;
const states = ['等待中', '已完成', '失败'];
const Account = () => {
  const [tabIndex, setTabIndex] = useState(0);
  const [exchangeVal, setExchangeVal] = useState(0);
  const [miningList, setMiningList] = useState([]);
  const [_amount, setAmount] = useState('');
  const [keepList, setKeepList] = useState([]);
  const [price, setPrice] = useState('0');
  const { address: _address } = useContext(AllContext);

  useEffect(() => {
    _getMiningList();
    _gePrice();
    time = setInterval(() => {
      _getMiningList();
    }, 5000);
    return () => clearInterval(time);
  }, []);

  const _getMiningList = async () => {
    if (falg) return;
    falg = true;
    try {
      const { msg, list = [] } = await getMiningList();
      falg = false;
      if (msg === 'success') {
        setMiningList(list);
      }
    } catch (error) {
      falg = false;
      console.log('_getMiningList', error);
    }
  };

  const _gePrice = async () => {
    try {
      const { price } = await getPrice();
      setPrice(price || 0);
    } catch (error) {}
  };

  const _withdraw = useCallback(async () => {
    if (!_address || !_amount) return;
    try {
      await withdraw({ address: _address, amount: _amount });
    } catch (error) {}
  }, [_address, _amount]);

  useEffect(() => {
    if (_address) {
      _getPledgeLog(_address);
    }
  }, [_address]);

  const _getPledgeLog = async (address) => {
    try {
      const { result = [] } = await getPledgeLog(address);
      setKeepList(result);
    } catch (error) {}
  };
  const _changeVal = (e) => {
    const val = e.target.value;
    setExchangeVal(val);
  };

  const _convert = useCallback(async () => {
    if (!_address || !exchangeVal) return;
    try {
      const { code, msg } = await convert({ address: _address, amount: exchangeVal });
      if (code !== 0) {
        Toast.show({
          content: msg,
          duration: 3000,
        });
      }
    } catch (error) {
      Toast.show({
        content: error,
        duration: 3000,
      });
    }
  }, [_address, exchangeVal]);

  return (
    <div>
      <Header />
      <div className={styles['ui-content']}>
        <div className={styles['ui-list']}>
          <div className={styles['ui-title']}>{'礦業'.LANG()}</div>
          <div className={styles['ui-info']}>
            <span>{'总产出'.LANG()}:</span>
            <span>0ETH</span>
          </div>
          <div className={styles['ui-info']}>
            <span>{'累计收益'.LANG()}:</span>
            <span>0USDT</span>
          </div>
          <div className={styles['ui-info']}>
            <span>{'日收益'.LANG()}:</span>
            <span>1%</span>
          </div>
          <div className={styles['ui-info']}>
            <span>{'今日收益'.LANG()}:</span>
            <span>0ETH</span>
          </div>
          <div className={styles['ui-info']}>
            <span>{'可提'.LANG()}:</span>
            <span>0USDT</span>
          </div>
        </div>

        <div className={styles['ui-tab']}>
          {tabs.map((item, index) => {
            return (
              <div
                className={index == tabIndex ? styles['select'] : styles['unselect']}
                key={index}
                onClick={() => setTabIndex(index)}
              >
                {item.LANG()}
              </div>
            );
          })}
        </div>
        {tabIndex === 0 && (
          <div className={styles['ui-exchange']}>
            <p className={styles['ui-exchange-tip']}>
              {'CoinBase {coin} 價格'.LANG({ coin: 'ETH' })}: {price}USDT
            </p>
            <div className={styles['ui-input']}>
              <input type="number" value={exchangeVal} onChange={_changeVal} />
              <div className={styles['right']}>
                <img src="images/usdt.png" alt="" />
                <span>USDT</span>
              </div>
            </div>
            <div className={styles['ui-all']}>
              <span>{'可用'.LANG()}:</span>
              <span>{'全部'.LANG()}</span>
            </div>
            <div className={styles['ui-icon']}>
              <img src="images/arrow_bottom.png" alt="" />
            </div>
            <div className={styles['ui-input']}>
              <div>{exchangeVal?.div(price)?.toFormat(6) || 0}</div>
              <div className={styles['right']}>
                <img src="images/eth.png" alt="" />
                <span>ETH</span>
              </div>
            </div>
            <div className={[styles['ui-confirm-btn'], styles['ui-btn']]} onClick={_convert}>
              {'确认'.LANG()}
            </div>
            <p className={styles['ui-center']}>
              {'將挖到的 {coin1} 幣兌換成 {coin2}'.LANG({
                coin1: 'ETH',
                coin2: 'USDT',
              })}
            </p>
          </div>
        )}
        {tabIndex === 1 && (
          <div className={styles['ui-exchange']}>
            <div className={styles['ui-prompt']}>
              <span>{'提示：仅支持提取USDT'}</span>
              <img src="images/eth.png" alt="" />
            </div>
            <div className={styles['ui-input']}>
              <input type="text" inputMode="decimal" value={_amount} onChange={(e) => setAmount(e.target.value)} />
              <div className={styles['right']}>
                <img src="images/usdt.png" alt="" />
                <span>USDT</span>
              </div>
            </div>
            <div className={[styles['ui-confirm-btn'], styles['ui-btn']]} onClick={_withdraw}>
              {'确认'.LANG()}
            </div>
            <p className={styles['ui-center']}>
              {'您的提現將在未來 24 小時內發送到您的 USDT 錢包地址。溫馨提示：每次取款都會扣除交易費用'.LANG()}
            </p>
          </div>
        )}
        {tabIndex === 2 && (
          <div className={styles['ui-list']}>
            <div className={styles['ui-title']}>{'記錄'.LANG()}</div>
            <ul className={styles['ui-record-tr']}>
              <li>{'時間'.LANG()}</li>
              <li>{'申請'.LANG()}</li>
              <li>{'状态'.LANG()}</li>
            </ul>
            {keepList.map(({ amount, time, state }, i) => {
              return (
                <ul className={[styles['ui-record-tr'], styles['ui-data']]} key={i}>
                  <li>{time}</li>
                  <li>{amount} ETH</li>
                  <li className={state === 2 ? styles['blue'] : styles['red']}>{states[state - 1]?.LANG()}</li>
                </ul>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};
export default Account;
